#!/usr/local/bin/python
# -*- coding: utf-8 -*
import xlrd
import json
import codecs
import os
import sys	 

from openpyxl import Workbook

application_path = os.path.dirname(__file__)
# outpath = "/files"
outpath = "/out"
 
cols = []

def JsonToExcel(file_path):
    print("打开Json文件:"+file_path)
    wb = Workbook()
    ws = wb.active
    with open(file_path, 'r', encoding='utf8') as fp:
        data = fp.read()
        fp.close()
        jsdata = json.loads(data)
        cols = [] # 字段名
        space = [] # 描述，此行留白
        types = [] # 类型
        # 第一行存key值，key值只参照第一个元素
        for k in jsdata[0].keys():
            cols.append(k)
            t = getValueType(jsdata[0].get(k))
            idx = 0
            while t is None and idx < len(jsdata) - 1:
                idx += 1
                t = getValueType(jsdata[idx].get(k))
            if t is None:
                print("字段" + k + "类型为空，请手动填入")
            types.append(t)
        ws.append(cols)
        ws.append(space)
        ws.append(types)

        for d in jsdata:
            rowdata = []
            for k in d.keys():
                if getValueType(d.get(k)) == 'Array':
                    rowdata.append(str(d.get(k)))
                else:
                    rowdata.append(d.get(k))
            ws.append(rowdata)
    file_name = file_path.split('/')[-1]
    path = str(os.getcwd()+outpath) + "/" + file_name.replace(".json", ".xlsx")
    wb.save(path)

def getValueType(value):
    if value is None:
        return None
    if type(value) is int:
        return 'Int'
    if type(value) is str:
        return 'String'
    if type(value) is bool:
        return 'Boolean'
    if type(value) is float:
        return 'Float'
    if type(value) is list:
        return 'Array'

#获取目录下所有文件
def getListFiles(path):
    ret = []
    for root, dirs, files in os.walk(path):
        for filespath in files:
            ret.append(os.path.join(root, filespath))
    return ret
 
 
if __name__ == '__main__':
    os.chdir(application_path)
    # path = os.path.join(os.getcwd(), "..") + "/assets/resources/configs/sheets"
    path = os.path.join(os.getcwd()) + "/files"

    with open('jsons', 'r', encoding='utf8') as fp:
        file_path = fp.readline()
        while (file_path != ''):
            if file_path.endswith(".json"):
                json_data = JsonToExcel(os.path.join(path, file_path))
            else:
                print("json文件路径不合法: "+file_path)
            file_path = fp.readline()
        fp.close()
    print("数据导出成功！！！")